package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;



    /**
     * 根据状态查询列表
     *
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        //1、参数校验
        if (authDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //检查分页参数
        authDto.checkParam();
        //2、执行查询

        IPage<ApUserRealname> pageParam = new Page<>(authDto.getPage(), authDto.getSize());

        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null) {
            query.eq(ApUserRealname::getStatus, authDto.getStatus());

        }
        IPage<ApUserRealname> pageResult = page(pageParam, query);

        //3、返回结果
        PageResponseResult result = new PageResponseResult(authDto.getPage(), authDto.getSize(), pageResult.getTotal(), pageResult.getRecords());

        return result;
    }

    /**
     * 根据状态审核
     *
     * @param authDto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto authDto, short status) {
        //1、参数检查
        if (authDto == null || authDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询apUserRealname信息
        ApUserRealname apUserRealname = getById(authDto.getId());
        if (apUserRealname == null || apUserRealname.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2、获取apUser的id
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        //判断apUser是否为空，并且状态是否被锁定
        if (apUser == null || apUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_STATUS_ERROR);
        }
        //3、修改状态  2：驳回  9：通过
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(authDto.getMsg())) {
            apUserRealname.setReason(authDto.getMsg());
        }
        updateById(apUserRealname);

        //4、如果审核通过
        if (apUserRealname.getStatus().intValue() == AdminConstants.PASS_AUTH) {
            //4.1、远程创建自媒体账号
            WmUser wmUser = createWmUser(authDto, apUser);
            if (wmUser == null || wmUser.getId() == null) {
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }
            //4.2、远程创建作者账号
            Boolean flag = createArticle(wmUser);
            if (!flag) {
                CustException.cust(AppHttpCodeEnum.ARTICLE_ADD_ERROR);
            }
            //5、更新apUser数据的 flag = 1
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }


        //6、返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 远程创建作者账号
     *
     * @param wmUser
     * @return
     */
    private Boolean createArticle(WmUser wmUser) {
        boolean flag = false;
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            System.out.println("---------" + wmUser.getName());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2);
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setWmUserId(wmUser.getId());
            ResponseResult result = articleFeign.save(apAuthor);
            if (result.getCode() == 0) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 远程创建自媒体账号
     *
     * @param authDto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(AuthDto authDto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setCreatedTime(new Date());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setApUserId(apUser.getId());
            wmUser.setImage(apUser.getImage());
            wmUser.setScore(100);
            wmUser.setStatus(9);
            wmUser.setType(0);

            //成功则主键回填
            return wemediaFeign.save(wmUser);
        }
        return null;
    }
}
